<template>
  <div class="p-4 mx-auto max-w-3xl">
    <h2 class="mb-4 text-xl font-bold">在线代码片段保存/分享</h2>
    
    <div class="grid grid-cols-1 gap-4 mb-4 md:grid-cols-3">
      <div class="md:col-span-2">
        <label class="block mb-1 font-medium text-gray-700">代码片段标题</label>
        <input 
          type="text" 
          v-model="snippetTitle" 
          class="p-2 w-full rounded border"
          placeholder="输入标题..." />
      </div>
      
      <div>
        <label class="block mb-1 font-medium text-gray-700">语言</label>
        <select v-model="language" class="p-2 w-full rounded border">
          <option value="javascript">JavaScript</option>
          <option value="typescript">TypeScript</option>
          <option value="html">HTML</option>
          <option value="css">CSS</option>
          <option value="java">Java</option>
          <option value="python">Python</option>
          <option value="go">Go</option>
          <option value="rust">Rust</option>
          <option value="c">C</option>
          <option value="cpp">C++</option>
          <option value="csharp">C#</option>
          <option value="php">PHP</option>
          <option value="ruby">Ruby</option>
          <option value="swift">Swift</option>
          <option value="kotlin">Kotlin</option>
          <option value="sql">SQL</option>
          <option value="bash">Bash</option>
          <option value="plaintext">纯文本</option>
        </select>
      </div>
    </div>
    
    <div class="mb-4">
      <textarea 
        v-model="code" 
        class="p-4 w-full h-80 font-mono text-sm rounded border"
        placeholder="// 在这里粘贴或输入你的代码..."
      ></textarea>
    </div>
    
    <div class="flex flex-wrap gap-2 mb-8">
      <button 
        @click="saveSnippet" 
        class="px-4 py-2 text-white bg-blue-500 rounded"
        :disabled="isSaving">
        {{ isSaving ? '保存中...' : '保存代码片段' }}
      </button>
      
      <button 
        @click="copyToClipboard" 
        class="px-4 py-2 text-white bg-purple-500 rounded">
        复制代码
      </button>
      
      <button 
        @click="downloadSnippet" 
        class="px-4 py-2 text-white bg-green-500 rounded">
        下载文件
      </button>
      
      <div class="ml-auto">
        <label class="inline-flex items-center">
          <input type="checkbox" v-model="isPrivate" class="w-5 h-5 form-checkbox" />
          <span class="ml-2">私有片段</span>
        </label>
      </div>
    </div>
    
    <!-- 分享链接 -->
    <div v-if="shareUrl" class="p-4 mb-6 bg-gray-100 rounded-lg">
      <h3 class="mb-2 font-bold">分享链接</h3>
      <div class="flex items-center">
        <input 
          type="text" 
          :value="shareUrl" 
          class="flex-1 p-2 rounded-l border" 
          readonly
        />
        <button 
          @click="copyShareUrl" 
          class="px-4 py-2 text-white bg-blue-500 rounded-r">
          复制
        </button>
      </div>
    </div>
    
    <!-- 已保存的代码片段列表 -->
    <div>
      <h3 class="mb-2 font-bold">我的代码片段</h3>
      <div class="overflow-hidden rounded-lg border">
        <div v-if="savedSnippets.length === 0" class="p-4 text-center text-gray-500">
          暂无保存的代码片段
        </div>
        <div v-else class="divide-y">
          <div 
            v-for="(snippet, index) in savedSnippets" 
            :key="index"
            class="p-3 hover:bg-gray-50">
            <div class="flex justify-between items-center">
              <div class="font-medium">{{ snippet.title || '无标题片段' }}</div>
              <div class="flex gap-2">
                <span class="px-2 py-1 text-xs bg-gray-200 rounded">{{ snippet.language }}</span>
                <button 
                  @click="loadSnippet(snippet)" 
                  class="px-2 py-1 text-xs text-white bg-blue-500 rounded">
                  加载
                </button>
                <button 
                  @click="deleteSnippet(index)" 
                  class="px-2 py-1 text-xs text-white bg-red-500 rounded">
                  删除
                </button>
              </div>
            </div>
            <div class="text-xs text-gray-500">
              保存于 {{ new Date(snippet.createdAt).toLocaleString() }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'

// 状态变量
const snippetTitle = ref('')
const language = ref('javascript')
const code = ref('')
const isPrivate = ref(false)
const shareUrl = ref('')
const isSaving = ref(false)
const savedSnippets = ref([])

// 加载保存的代码片段
onMounted(() => {
  const storedSnippets = localStorage.getItem('codeSnippets')
  if (storedSnippets) {
    savedSnippets.value = JSON.parse(storedSnippets)
  }
})

// 保存代码片段
function saveSnippet() {
  if (code.value.trim() === '') {
    alert('请输入代码内容')
    return
  }
  
  isSaving.value = true
  
  // 在实际项目中，这里应该是API调用
  // 这里我们用localStorage模拟
  setTimeout(() => {
    const snippet = {
      id: generateId(),
      title: snippetTitle.value || `未命名片段 ${new Date().toLocaleString()}`,
      language: language.value,
      code: code.value,
      isPrivate: isPrivate.value,
      createdAt: new Date().getTime()
    }
    
    savedSnippets.value.unshift(snippet)
    localStorage.setItem('codeSnippets', JSON.stringify(savedSnippets.value))
    
    // 生成分享链接
    shareUrl.value = `${window.location.origin}/snippet/${snippet.id}`
    
    isSaving.value = false
  }, 700) // 模拟API延迟
}

// 生成唯一ID
function generateId() {
  return Date.now().toString(36) + Math.random().toString(36).substr(2)
}

// 复制代码到剪贴板
function copyToClipboard() {
  if (code.value.trim() === '') {
    alert('没有可复制的代码')
    return
  }
  
  navigator.clipboard.writeText(code.value)
    .then(() => {
      alert('代码已复制到剪贴板')
    })
    .catch(err => {
      console.error('复制失败:', err)
      alert('复制失败，请手动复制')
    })
}

// 复制分享链接
function copyShareUrl() {
  navigator.clipboard.writeText(shareUrl.value)
    .then(() => {
      alert('分享链接已复制到剪贴板')
    })
    .catch(err => {
      console.error('复制失败:', err)
      alert('复制失败，请手动复制')
    })
}

// 下载代码片段
function downloadSnippet() {
  if (code.value.trim() === '') {
    alert('没有可下载的代码')
    return
  }
  
  // 确定文件扩展名
  let extension = '.txt'
  switch (language.value) {
    case 'javascript': extension = '.js'; break
    case 'typescript': extension = '.ts'; break
    case 'html': extension = '.html'; break
    case 'css': extension = '.css'; break
    case 'python': extension = '.py'; break
    case 'java': extension = '.java'; break
    case 'go': extension = '.go'; break
    case 'rust': extension = '.rs'; break
    case 'c': extension = '.c'; break
    case 'cpp': extension = '.cpp'; break
    case 'csharp': extension = '.cs'; break
    case 'php': extension = '.php'; break
    case 'ruby': extension = '.rb'; break
    case 'swift': extension = '.swift'; break
    case 'kotlin': extension = '.kt'; break
    case 'sql': extension = '.sql'; break
    case 'bash': extension = '.sh'; break
  }
  
  const fileName = (snippetTitle.value || 'code-snippet') + extension
  const blob = new Blob([code.value], { type: 'text/plain' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = fileName
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
}

// 加载代码片段
function loadSnippet(snippet) {
  if (code.value.trim() !== '' && !confirm('加载此代码片段将覆盖当前内容，是否继续？')) {
    return
  }
  
  snippetTitle.value = snippet.title
  language.value = snippet.language
  code.value = snippet.code
  isPrivate.value = snippet.isPrivate
  
  // 滚动到编辑区
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

// 删除代码片段
function deleteSnippet(index) {
  if (!confirm('确定要删除此代码片段吗？此操作不可撤销。')) {
    return
  }
  
  savedSnippets.value.splice(index, 1)
  localStorage.setItem('codeSnippets', JSON.stringify(savedSnippets.value))
  
  // 如果正在显示此代码片段的分享链接，则清除
  shareUrl.value = ''
}
</script> 